<template>
	<div class="page">
		<div class="form-view c-panel">
		<Form ref="form" :model="params" :rules="rules" :label-width="80">
			<Form-item label="作品属性" style="width: 300px;" prop="attribute">
				<Select 
					v-model="params.attribute" 
					size="large"
					@on-change="selectAttribute">
			        <Option 
			        		v-for="(item, index) in initData.attributes" 
			        		:value="item.aid" 
			        		:key="index"
			        		v-text="item.name">
			        </Option>
			   </Select>
			</Form-item>
			
			<Form-item label="作品名称" style="width: 300px;" prop="name">
				<Input v-model="params.name" placeholder="作品名称" size="large"></Input>
			</Form-item>
			
			<Form-item 
				label="作品类型" 
				style="width: 500px;" 
				prop="types">
				<Select v-model="params.types" 
					multiple
					size="large">
					<Option 
						v-for="(item, index) in initData.types" 
						:value="item.tid" 
						:key="index"
						v-text="item.name">
					</Option>
				</Select>
			</Form-item>
			
			<Form-item label="海报" prop="poster.url"
				:rules="{required: true, type: 'string', message: '作品海报不能为空', trigger: 'change'}">
				<CImageCropper
					:progress="posterProgress"
					:durl="params.poster.url"
					@upload-data="uploadPoster">
				</CImageCropper>
			</Form-item>
			<Form-item label="上映日期" prop="releaseDate">
				<div>
					<Input-number 
						:max="2030" 
						:min="1900" 
						v-model="params.releaseDate.year" 
						size="large" 
						style="width: 80px;">
					</Input-number>
					<span class="r-date r-year">年</span>
				    <Input-number 
						:max="12" 
						:min="0" 
						v-model="params.releaseDate.month" 
						size="large" 
						style="width: 60px;">
					</Input-number>
				    <span class="r-date r-month">月</span>
				    <Input-number 
						:max="31" 
						:min="0" 
						v-model="params.releaseDate.day" 
						size="large" 
						style="width: 60px;">
					</Input-number>
				    <span class="r-date r-day">日</span>
			    </div>
			</Form-item>
			
			<Form-item label="上映地区" 
				prop="releaseArea.areaId"
				style="width: 300px;"
				:rules="[{required: true, type: 'integer', message: '上映地区不能为空', trigger: 'blur'},
				{required: true, type: 'integer', message: '上映地区不能为空', trigger: 'change'}]">
				<Select 
					v-model="params.releaseArea.areaId" 
					size="large" 
					@on-change="selectArea">
			        <Option 
			        		v-for="(item, index) in initData.areas" 
			        		:value="item.aid" 
			        		:key="index"
			        		v-text="item.name">
			        </Option>
			   </Select>
			</Form-item>

			<Form-item label="其他地区" style="width: 300px;" v-if="params.releaseArea.isSet">
				<Input v-model="params.releaseArea.name" placeholder="其他地区" size="large"></Input>
			</Form-item>
			
			<Form-item 
				label="片长" 
				v-if="params.attrObj != null && params.attrObj.hasDuration == 1">
				<Input-number 
					:max="300" 
					:min="10" 
					v-model="params.duration" 
					size="large" 
					style="width: 80px;">
				</Input-number>
				<span class="duration">分钟</span>
			</Form-item>
			
			<Form-item label="集数"
				v-if="params.attrObj != null && params.attrObj.hasEpisodes == 1">
				<Input-number 
					:max="300" 
					:min="1" 
					v-model="params.episodes" 
					size="large" 
					style="width: 80px;">
				</Input-number>
				<span class="duration">集</span>
			</Form-item>
			
			<Form-item label="票房"
				v-if="params.attrObj != null && params.attrObj.hasBoxOffice == 1">
				<div class="boxOffice-item">
					<Input-number 
						:min="0" 
						v-model="params.boxOffice" 
						size="large" 
						style="width: 80px; margin-right: 20px;">
					</Input-number>
					<Radio-group v-model="params.boxOfficeType" type="button" size="large">
				        <Radio label="1">亿元</Radio>
				        <Radio label="2">万元</Radio>
				    </Radio-group>
			   </div>
			</Form-item>
		</Form>
			<div class="btns-view">
	        		<Button type="primary" 
	        			@click="handleSubmit('form')" 
	        			:loading="isShowLoading"
	        			long size="large">提交</Button>
	        		<Button type="ghost" 
	        			@click="handleReset('form')" 
	        			style="margin-left: 20px"
	        			:disabled="isShowLoading"
	        			long size="large">重置</Button>
			</div>
		</div>
	</div>
</template>

<script>
	import WorksService from '@/services/WorksService.js';
	import WAttrService from '@/services/WAttrService.js';
	import WTypeService from '@/services/WTypeService.js';
	import WAreaService from '@/services/WAreaService.js';
	import QiniuService from '@/services/QiniuService.js';
	import CImageCropper from '@/components/CImageCropper.vue';
	import AppConfig from '@/constants/AppConfig.js';

	var $app_config = AppConfig();
	var $worksService = WorksService();
	var $wAttrService = WAttrService();
	var $wTypeService = WTypeService();
	var $wAreaService = WAreaService();
	var $qiniuService = QiniuService();
	var $this = null;
	const $data = {
		isShowLoading: false,
		isPageLoading: false,
		posterProgress: 0,
		params: {
			worksId: null,
			attribute: null,
			attrObj: null,
			name: '',
			poster: {
				url: null,
				key: null,
				width: 0,
				height: 0
			},
			types: [],
			releaseDate: {
				year: 2000,
				month: 10,
				day: 1
			},
			releaseArea: {
				isSet: false,
				areaId: 0,
				name: null
			},
			duration: 0,
			boxOfficeType: 2,
			boxOffice: 0,
			episodes: 1
		},
		initData: {
			attributes: [],
			types: [],
			areas: []
		},
		rules: {
			attribute: [
                { required: true, type: 'integer', message: '属性不能为空', trigger: 'change' }
            ],
            name: [
                { required: true, message: '作品名称不能为空', trigger: 'blur' }
            ],
            types: [
                { required: true, type: 'array', message: '作品类型不能为空', trigger: 'change' }
            ]
        }
	}
	//属性
	function getAttrs() {
		$wAttrService.getWorksAttrs()
			.then(function(response) {
				var res = response.data;
				var code = res.rescode;
				if(code == 100) {
					var data = res.data;
					$data.initData.attributes = data;
					if(data.length > 0) {
						$data.params.attribute = data[0].aid;
						$data.params.attrObj = data[0];
					}
				}
			}, function(error) {
				console.log(error);
			});
	}
	//类型
	function getTypes() {
		$wTypeService.getWorksTypes()
			.then(function(response) {
				var res = response.data;
				var code = res.rescode;
				if(code == 100) {
					var data = res.data;
					$data.initData.types = data;
				}
			}, function(error) {
				console.log(error);
			});
	}
	//地区
	function getAreas() {
		$wAreaService.getWorksAreas()
			.then(function(response) {
				var res = response.data;
				var code = res.rescode;
				if(code == 100) {
					var data = res.data;
					$data.initData.areas = data;
					if(data.length > 0) {
						$this.params.releaseArea.areaId = data[0].aid;
					}
				}
			}, function(error) {
				console.log(error);
			});
	}
	function getWorksDetail(wid) {
		$worksService.getWorksDetail(wid)
			.then(function(response) {
				var res = response.data;
				var code = res.rescode;
				if(code == 100) {
					var data = res.data;
					var posterJson = data.poster;
					var poster = eval('(' + posterJson + ')');
					var dateType = data.dateType;
					var releaseDate = {
						year: data.releaseYear,
						month: 0,
						day: 0
					}
					if(dateType == 2) {
						var month = data.releaseDate.split('-')[1];
						if(month.indexOf('0') == 0) {
							month = month.substr(1);
						}
						releaseDate = {
							year: data.releaseYear,
							month: parseInt(month),
							day: 0
						}
					} else if(dateType == 3) {
						var month = data.releaseDate.split('-')[1];
						if(month.indexOf('0') == 0) {
							month = month.substr(1);
						}
						var day = data.releaseDate.split('-')[2];
						if(day.indexOf('0') == 0) {
							day = day.substr(1);
						}
						releaseDate = {
							year: data.releaseYear,
							month: parseInt(month),
							day: parseInt(day)
						}
					}
					//类型
					var typesId = [];
					data.typeIds.forEach(function(value, index, array) {
						typesId.push(parseInt(value));
					});
					$data.params = {
						worksId: wid,
						attribute: data.attribute.aid,
						attrObj: data.attribute,
						name: data.name,
						poster: {
							url: poster.url,
							key: poster.key,
							width: poster.width,
							height: poster.height
						},
						types: typesId,
						releaseDate: releaseDate,
						releaseArea: {
							isSet: false,
							areaId: data.releaseArea,
							name: data.areaName
						},
						duration: data.duration,
						boxOfficeType: data.boxOffice > 10000 ? 1:2,
						boxOffice: data.boxOffice > 10000? data.boxOffice/10000 : data.boxOffice,
						episodes: data.episodes
					}
				}
				$data.isPageLoading = false;
			}, function(error) {
				$data.isPageLoading = false;
			});
	}
	export default {
		name: 'WorksEditPage',
		data() {
			return $data;
		},
		components: {
			CImageCropper
		},
		created() {
			getAttrs();
			getTypes();
			getAreas();
		},
		mounted() {
			$this = this;
			$data.params.worksId = this.$route.query.wid;
			if($data.params.worksId != null) {
				$data.isPageLoading = true;
				getWorksDetail($data.params.worksId);
			}
		},
		methods: {
			selectArea(aid) {
				for (var i=0; i<$data.initData.areas.length; i++) {
					var item = $data.initData.areas[i];
					if(aid == item.aid) {
						$data.params.releaseArea.isSet = (item.isSet == 1);
						break;
					}
				}
			},
			selectAttribute(aid) {
				for (var i=0; i< $data.initData.attributes.length; i++) {
					var item = $data.initData.attributes[i];
					if(aid == item.aid) {
						$data.params.attrObj = item;
						break;
					}
				}
			},
			uploadPoster(data) {//上传图片
				$qiniuService.uploadBase642QiniuServer(data, function() {
				}, function(e) {
					if (e.lengthComputable) {//进度信息是否可用
						console.log(e);
						$this.posterProgress = e.loaded / e.total * 100;
					}
				})
				.then(function(response) {
					if(response.state == 1) {//成功
						$this.posterProgress = 100;
						self.deployTimeOutId = setTimeout(() => {
							$this.posterProgress = 0;
                        }, 1000);		
                        var data = JSON.parse(response.data);
                        console.log(data);
                        $this.params.poster = {
                        		url: $app_config.QiNiu.imageServer + data.key,
                        		key: data.key,
                        		width: data.imgW,
                        		height: data.imgH
                        }
					}
				}, function(error) {
					$this.$Message.error(error);
				});
			},
			handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                    		$data.isShowLoading = true;
                    		var t = $data.params;
                    		var dateType = 1;
                    		var releaseDate = t.releaseDate.year;
                    		if(t.releaseDate.month > 0) {
                    			var y = t.releaseDate.year;
                    			var m = t.releaseDate.month < 10? ('0' + t.releaseDate.month) : t.releaseDate.month;
                    			if (t.releaseDate.day == 0) {
                    				releaseDate = y + '-' +  m;
	                    			dateType = 2;
	                    		} else {
	                    			var d = t.releaseDate.day < 10? ('0' + t.releaseDate.day) : t.releaseDate.day;
	                    			releaseDate = y + '-' +  m + '-' + d;
	                    			dateType = 3;
	                    		}
                    		}
                    		
                    		var boxOffice = t.boxOffice;
                    		//票房
                    		if(t.boxOfficeType == 1) {
                    			boxOffice = boxOffice * 10000;
                    		}
                    		console.log(dateType);
                    		var params = {
                    			worksId: t.worksId,//	string	32位数字字母	作品id
							attribute: t.attribute, //	string	0	作品属性
							name	: t.name, //String	作品名称	作品名称
							types: JSON.stringify(t.types), //	string	['','']	类型
							poster: JSON.stringify(t.poster), // 	string	海报地址	类型
							dateType: dateType,
							releaseDate: releaseDate,//	string	1900-09-01	上映日期
							releaseYear: t.releaseDate.year, //	string	1900	上映年份
							releaseArea: t.releaseArea.areaId, //		int	1	上映地区
							areaName: t.releaseArea.name,
							duration	: t.duration, //	int	90	片长
							boxOffice: boxOffice, //		int	3200	1000万元
							episodes: t.episodes, //		int	10	集数
                    		};
                    		$worksService.editWorks(params)
                    		.then(function(response) {
                    			var res = response.data;
							var code = res.rescode;
							var msg = res.msg;
							if(code == 100) {
								var data = res.data;
								$this.$router.push({name: 'worksDetail', query: {wid: data.wid}});
								$this.$Message.success(msg);
							} else {
								$this.$Message.error(msg);
							}
                    			$data.isShowLoading = false;
                    		}, function(error) {
                    			console.log(error);
                    			$data.isShowLoading = false;
                    		});
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            }
		}
	}
</script>

<style scoped="scoped">
	.page {
	}
	
	.form-view {
		width: 800px;
		padding: 30px 50px;
		margin: 0 auto;
	}
	
	.btns-view {
		margin-top: 50px;
		display: flex;
		display: -webkit-flex;
		display: -moz-flex;
	}
	
	.r-date, .duration {
		padding: 0px 8px;
		font-size: 14px;
	}
	
	.boxOffice-item {
		align-items: center;
		-webkit-align-items: center;
		-moz-align-items: center;
		display: flex;
		display: -webkit-flex;
		display: -moz-flex;
	}
	@keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
    .spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>